package com.watson.juc.testlist;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

/**
 * 如何使用Fork Join
 * 1.ForkJoinPool
 * 2.ForkJoinTask  实现类==> RecursiveAction 递归事件  无返回值
 * RecursiveTask    递归任务 有返回值
 **/
public class ForkJoinTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test01();
        test02();
        test03();
    }

    public static void test01() {
        Long start = System.currentTimeMillis();
        Long sum = 0L;
        for (Long i = 1L; i <= 100000000L; i++) {
            sum += i;
        }
        Long end = System.currentTimeMillis();
        System.out.println("值" + sum + "时间" + (end - start));
    }

    public static void test02() throws ExecutionException, InterruptedException {
        Long start = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinDemo(0L, 100000000L);
//        forkJoinPool.execute(task);
//        Long sum = task.get();
        //提交任务异步的
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);
        Long sum = submit.get();
        Long end = System.currentTimeMillis();
        System.out.println("值" + sum + "时间" + (end - start));
    }

    public static void test03() {
        Long start = System.currentTimeMillis();
        Long sum = LongStream.rangeClosed(0L, 100000000L).reduce(0, Long::sum);
        Long end = System.currentTimeMillis();
        System.out.println("值" + sum + "时间" + (end - start));
    }
}

